<template>
  <div class="filterBox" >
    <el-popover
        :visible="state.visible"
      placement="bottom"
    >
      <template #reference>
            <div 
      ref="buttonRef"
  @click="handleShow"
      class="aic cP"
      :style="align == 'left' ? {} : { justifyContent: 'center' }"
    >
      {{ title }}
      <div v-if="isFilter" class="fdc aic pl-5"
      style=" margin-left: 5px;"
      >
       
        <el-icon
         @click.stop="handleOrder('asc')"
         style=" color: #9999;height:0.6rem" :class="[
            state.isTop ? 'colorActive' : '',
            '',
          ]"><CaretTop /></el-icon>


          <el-icon 
            @click.stop="handleOrder('desc')"
          style=" color: #9999;height:0.6rem" :class="[
            state.isBottom ? 'colorActive' : '',
           ,
          ]"><CaretBottom /></el-icon>
      </div>
      <el-icon
        v-if="!isFilter"
        style="font-size: 14px; margin-left: 5px;"
        :class="[
          state.values.length > 0 || state.value ? 'colorActive' : 'loudou',
        ]"
        ><iconLouDou
      /></el-icon>
    </div>
      </template>
      <div v-click-outside="onClickOutside">
        <div v-if="flterType == 'select'">
          <el-input
            placeholder="请输入内容"
            v-model="filterKey"
            size="mini"
            @change="handleFilter"
            clearable
          >
          </el-input>

          <el-checkbox-group
            v-model="state.values"
            class="overflowY mt10"
            style="height: 100px"
          >
            <el-checkbox
              class=""
              v-for="(item, index) in state.options"
              :key="index"
              :label="item"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
          <div
            style="
              border-top: 1px solid #dddfe6;
              text-align: center;
              padding-top: 15px;
            "
          >
            <el-button size="mini" @click="handleSearch" type="primary"
              >确定</el-button
            >
            <el-button size="mini" @click="cancelBtn">取消</el-button>
          </div>
        </div>
        <div v-if="flterType == 'input'">
          <el-input
            placeholder="请输入内容 后回车"
            v-model="state.value"
            ref="inputKey"
            @keyup.enter.native="handleInputData(state.value)"
            clearable
          >
          </el-input>
        </div>
        <div v-if="flterType == 'number'">
          <el-input
            placeholder="请输入内容 后回车"
            v-model="state.value"
            ref="inputKey"
            type="number"
            @keyup.enter.native="handleInputData(state.value)"
            clearable
          >
          </el-input>
        </div>
        <div v-if="flterType == 'datetimerange'" >
          <el-date-picker
            v-model="state.values"
            type="datetimerange"
            :teleported="false"
            range-separator="至"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            @change="handleFilterDate"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </div>
        <div v-if="flterType == 'daterange'">
          <el-date-picker
            v-model="state.values"
            type="daterange"
            :teleported="false"
            range-separator="至"
            value-format="YYYY-MM-DD"
            @change="handleFilterDate"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </div>
        <div v-if="flterType == 'years'" >
          <el-date-picker 
            v-model="state.values"
            value-format="YYYY"
            type="years"
            @change="handleFilterYears"
          >
          </el-date-picker>
        </div>
        <div v-if="flterType == 'month'">
          <el-date-picker
            v-model="state.value"
            value-format="YYYY-MM"
            type="month"
            placeholder="请选择"
            @change="handleInputData"
          >
          </el-date-picker>
        </div>
        <div v-if="flterType == 'months'">
          <el-date-picker
            v-model="state.values"
            format="YYYY-MM"
             value-format="YYYY-MM"
             type="months"  placeholder="请选择"
            @change="handleFilterYears"
          >
          </el-date-picker>
        </div>
      </div>
    </el-popover>
  </div>
</template>

<script setup lang="tsx">
import {
  ref,
  reactive,
  defineEmits,
  onMounted,
  nextTick,
  computed,
  watch,
  toRaw,
  unref,
} from "vue";
const emit = defineEmits(["change","sort"]);
import filterTag from "/@/components/Filter/filterTag.vue";
import { getDicts } from "/@ts/axios/urlApi/system";
import { useIndexStore } from "/@ts/store/index";
const store = useIndexStore();
import { ClickOutside as vClickOutside } from "element-plus";
// const store  = useStops()
const state: any = reactive({
  filterKey: "",
  isTop: false,
  isBottom: false,
  show: false,
  options: [],
  optionsCopy: [],
  values: [],
  years: "",
  value: "",
  deptOptions: [],
  allDeptList: [],
  visible: false,
});
const handleShow = () =>{
state.visible = true
}
const props: any = defineProps({
  valueKey: {
    //api 对应的函数 名字
    type: String,
    default: "",
  },
  params: {
    //api 传递 的 参数
    type: Object,
    default: () => {},
  },
  title: {
    //标题名字
    type: String,
    default: "",
  },
  isFilter: {
    // 是否有 排序
    type: Boolean,
    default: false,
  },
  orderDef: {
    type: String,
    default: "",
  },
  dictCode: {
    type: String,
    default: "",
  },
  flterType: {
    //筛选类型  ==""&&isFilter==true 为 排序模式
    type: String,
    default: "select",
  },
  width: {
    //筛选类型
    type: [Number, String],
    default: 200,
  },
  data: {
    //数据同步 字段
    type: [Number, String, Array, Object],
    default: () => {},
  },
  list: {
    //筛选数据
    type: Array,
    default: () => [],
  },
  align: {
    type: String,
    default: "left",
  },
});

watch(
  () => props.data,
  (val) => {
    if (val) {
      
      const values = val[props.valueKey];
      // console.log("values :>> ", values);
      if (!values) {
        state.values = [];
        state.value = "";
        closePopover();
        
        return;
      }

      const dataType = ["years", "datetimerange", "daterange"];
      if (dataType.includes(props.flterType)) {
        state.values = values.map((res: any) => res.value);
      }
      const dataType3 = ["input", "number"];
      if (dataType3.includes(props.flterType)) {
        if (values.length == 0) {
          state.value = "";
          closePopover();
           
        }
      }
    }
  },
  {
    deep: true,
  }
);

const buttonRef = ref();
const popoverRef = ref();
const onClickOutside = () => {
  closePopover();
  // onClickOutside
    
};
const handleOrder = (type:string) =>{
     let data = {
        order: ''
      }
     if (type == 'desc') {
        state.isBottom = !state.isBottom
        state.isTop = false
        if(state.isBottom){
          data.order = 'desc'
        }else{
          data.order = ''
        }
      } else {
        state.isTop = !state.isTop
        if(state.isTop){
          data.order = 'asc'
        }else{
          data.order = ''
        }
        state.isBottom = false
      }
   

        emit("sort", {
    data: data,
    valueKey: props.valueKey,
    title: props.title,
    
  });
}
const handleFilter = () => {
  if (state.filterKey == "") {
    state.options = state.optionsCopy;
    return;
  }
  state.options = state.optionsCopy.filter((res: any) => {
    if (res.label.indexOf(state.filterKey) != -1) return res;
  });
};
const closePopover = () => {
  state.visible = false
  window.log.info("closePopover","隐藏了");
};
const handleSearch = () => {
    closePopover();
  emit("change", {
    data: state.values,
    valueKey: props.valueKey,
    title: props.title,
    type: "multi",
  });
};
const cancelBtn = () => {
  closePopover();
};
const getData = (key: any) => {
  getDicts(key).then((response: any) => {
    state.options = response.data.map((item: any) => {
      return {
        label: item.dictLabel,
        value: item.dictValue,
        raw: item,
      };
    });
    state.optionsCopy = toRaw(state.options);
  });
};
const handleClose = (val: any) => {
  if (props.flterType != "user") {
    closePopover();
  }
};
const handleFilterDate = (val: any) => {
  closePopover();
  emit("change", {
    data: [
      {
        value: val,
        label: `${val[0]}~${val[1]}`,
      },
    ],
    valueKey: props.valueKey,
    title: props.title,
    type: "single",
  });
};
const handleFilterYears = (val: any) => {
  closePopover();
  if (val) {
    emit("change", {
      data: val.map((res: any) => {
        return {
          value: res,
          label: res,
        };
      }),
      valueKey: props.valueKey,
      title: props.title,
      type: "multi",
    });
  } else {
    emit("change", {
      data: [],
      valueKey: props.valueKey,
      title: props.title,
      type: "multi",
    });
  }
};
const handleInputData = (val: any) => {
  let data: any = [];
  if (val) {
    data = [
      {
        value: val,
        label: val,
      },
    ];
  }
  emit("change", {
    data: data,
    valueKey: props.valueKey,
    title: props.title,
    type: "single",
  });
 closePopover();
};

watch(
  () => props.dictCode,
  (val: any) => {
    if (val) {
      if (state.options.length == 0) {
        getData(val);
      }
    }
  },
  {
    deep: true,
    immediate: true,
  }
);
</script>

<style lang="scss">
.colorActive {
  color: var(--el-color-primary)!important;
}
.filterBtn:hover {
  color: var(--el-color-primary)!important;
}
.loudou {
  color: var(--el-text-color-secondary);
}
.filterBox.el-popover.popperClass {
  min-width: 80px;
  z-index: 1000 !important;
}
.el-popover.el-popper {
  width: auto !important;
}
</style>
